﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Microsoft.Office.Interop.Excel;
using PanGu;

namespace PatientInformationExtract.MainInterface.Models.XMLCS
{
    /// <summary>
    /// 管理所有病人信息类，并能导出XML
    /// </summary>
    public class EventLog
    {
        private XmlDocument _xml;
        public XmlDocument XMLDoc { get { return this._xml; } }
        private List<PatientInfo> _patientInfos;
        public List<PatientInfo> PatientInfos { get { return this._patientInfos; } }
        private XmlElement _rootElement;
        private Workbooks _excelWBs;
        private ParseOption _option;
        public ParseOption Option { get { return this._option; } }
        public XmlDocument EncodingDictionaryDoc { get { return Segment.GetEncodeDictionaryXml(); } }

        public EventLog(Workbooks excelWBs)
        {
            _xml = new XmlDocument();
            XmlDeclaration xmlDeclaration = _xml.CreateXmlDeclaration("1.0", "UTF-8", "yes");
            _xml.AppendChild(xmlDeclaration);
            _rootElement = _xml.CreateElement("EventLogGeneratedByPIES");
            _patientInfos = new List<PatientInfo>();
            _excelWBs = excelWBs;
            _option = new ParseOption();
        }

        public void DeleteAllPatientInfo()
        {
            _patientInfos = new List<PatientInfo>();
        }

        public bool DeletePatientInfoByFolderPath(string folderPath)
        {
            foreach (PatientInfo pi in _patientInfos.ToArray())
            {
                if (pi.FoderPath.Equals(folderPath))
                {
                    _patientInfos.Remove(pi);
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 新增病人信息类，将字段Xml传递给病人信息类
        /// </summary>
        /// <returns>返回新增的病人信息类</returns>
        public PatientInfo AddPatientInfo()
        {
            PatientInfo pi = new PatientInfo(ref _xml, ref _excelWBs, this);
            this._patientInfos.Add(pi);
            return pi;
        }

        /// <summary>
        /// 将PatientTace元素添加到Eventlog元素下
        /// </summary>
        public void Update()
        {
            _xml.RemoveAll();
            _rootElement.RemoveAll();
            if (this._option.IsEncoded)
            {
                _rootElement.SetAttribute("Encoding", "Yes");
            }
            else
            {
                _rootElement.SetAttribute("Encoding", "No");
            }
            foreach (PatientInfo pi in _patientInfos)
            {
                pi.Update();
                _rootElement.AppendChild(pi.PatientTrace);
            }
            _xml.AppendChild(_rootElement);
        }
    }
}
